package com.yjc.spring.boot.postprocessor;

import com.yjc.manager.holder.ClassHolder;
import com.yjc.spring.boot.context.DynamicLoadSpringContext;
import com.yjc.spring.boot.yaml.YamlConfig;
import com.yjc.spring.boot.yaml.YamlConfigFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;


import java.util.Map;

public class ClassHolderBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    //提前获取配置文件的数据，因为BeanFactoryPostProcessor执行时，对象信息都还没开始实例化
    private YamlConfig consumerYamlConfig = YamlConfigFactory.getConcumerYamlConfig();

    public ClassHolderBeanFactoryPostProcessor() {
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        DynamicLoadSpringContext.getInstance().setContext(beanFactory);
        //loadClass
        String pathName = consumerYamlConfig.getPathName();
        ClassHolder classHolder = ClassHolder.getInstance();
        classHolder.loadClass(pathName);
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        //将加载的类注入到spring
        Map<String, Map<Class<?>, Class<?>>> jarInterfaceMap = classHolder.getJarInterfaceMap();
        for (Map.Entry<String, Map<Class<?>, Class<?>>> jarEntry : jarInterfaceMap.entrySet()) {
            String jarName = jarEntry.getKey();
            for (Map.Entry<Class<?>, Class<?>> interfaceClassEntry : jarEntry.getValue().entrySet()) {
                Class<?> interfaceClass = interfaceClassEntry.getKey();
                Class<?> clazz = interfaceClassEntry.getValue();
                BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz);
                AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
                registry.registerBeanDefinition(getBeanName(jarName,interfaceClass),beanDefinition);
            }
        }
    }

    private String getBeanName(String jarName,Class<?> interfaceClass){
        return jarName + "." + interfaceClass.getName();
    }
}
